---
description: Learn how to configure GraphQL Code Generator to generate code from your GraphQL schema and documents.
---

import { Callout } from '@theguild/components'

# `codegen.ts` file

[The plugins' page](/plugins) lists dozens of plugins with their set of options and specific outputs.

GraphQL Code Generator relies on a configuration file named `codegen.ts` to manage all possible options, input, and output document types.

The CLI automatically detects the defined config file and generates code accordingly.

In addition, you can also define a path to your config file with the `--config` options, like so:

```sh
npx graphql-code-generator --config ./path/to/codegen.ts
```

## Configuration file format

Here's an example for a possible config file:

```ts
import { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: ['src/**/*.tsx'],
  generates: {
    './src/gql/': {
      preset: 'client'
    }
  }
}

export default config
```

## Configuration options

Here are the supported options that you can define in the config file (see [source code](https://github.com/dotansimha/graphql-code-generator/blob/master/packages/utils/plugins-helpers/src/types.ts#L388)):

- [**`schema` (required)**](./schema-field#root-level) - A URL to your GraphQL endpoint, a local path to `.graphql` file, a glob pattern to your GraphQL schema files, or a JavaScript file that exports the schema to generate code from. This can also be an array that specifies multiple schemas to generate code from. You can read more about the supported formats [here](./schema-field#available-formats)

- [**`documents`**](./documents-field#root-level) - Array of paths or glob patterns for files which export GraphQL documents using a `gql` tag or a plain string; for example: `./src/**/*.graphql`. You can also provide these options with a string instead of an array if you're dealing with a single document. You can read more about the supported formats [here](./documents-field#available-formats)

- **`generates` (required)** - A map where the key represents an output path for the generated code, and the value represents a set of relevant options for that specific file. Below are the possible options that can be specified:

  - **`generates.plugins` (required)** - A list of plugins to use when generating the file. Templates, considered as plugins, can be specified in this section. A complete list of supported plugins is available [here](/plugins). You can also point to a custom plugin in a local file (see [Custom Plugins](/docs/custom-codegen))

  - **`generates.preset`** - A list of presets to use for the output. Presets are a way to dynamically create the list of output files based on the input schema. [`near-operation-file-preset`](/plugins/near-operation-file-preset) is a good example

  - [**`generates.schema`**](./schema-field#output-file-level) - Same as root `schema`, but applies only for the specific output file

  - [**`generates.documents`**](./documents-field#output-file-level) - Same as root `documents`, but applies only for the specific output file

  - [**`generates.config`**](./config-field#output-level) - Same as root `config`, but applies only for the specific output file

  - **`generates.overwrite`** - Same as root `overwrite`, but applies only for the specific output file

- [**`require`**](./require-field) - A path to a file which defines custom Node.JS `require()` handlers for custom file extensions. This option is essential if the code generator has to go through files that require other files in an unsupported format ([more information](https://gist.github.com/jamestalmage/df922691475cff66c7e6)). Note that values specified in your `.yml` file get loaded after loading the `.yml` file

- [**`config`**](./config-field#root-level) - Options we would like to provide to the specified plugins. The options may vary depending on what plugins you specified. Read the documentation of that specific plugin for more information. You can read more about passing configuration to plugins [here](./config-field)

- **`overwrite`** - A flag to overwrite files if they already exist when generating code (`true` by default)

- **`watch`** - A flag to trigger codegen when there are changes in the specified GraphQL schemas. You can either specify a boolean to turn it on/off or specify an array of glob patterns to add custom files to the watch. When in watch mode, partial success still writes to files.

- **`silent`** - A flag to suppress printing errors when they occur

- **`noSilentErrors`** - A flag to raise errors if any matched files are not valid GraphQL

- **`debug`** - A flag to enable printing debug logs

- **`verbose`** - A flag to enable tasks verbose mode

- **`ignoreNoDocuments`** - A flag to not exit with non-zero exit code when there are no documents

- **`importExtension`** - Append this extension to all imports.

- **`errorsOnly`** - A flag to suppress printing anything except errors.

- **`hooks`** - Specifies scripts to run when events are happening in the codegen's core. You can read more about lifecycle hooks [here](./lifecycle-hooks). You can specify this on your root configuration or on each output

- **`pluginLoader`** - If you are using the programmatic API in a browser environment, you can override this configuration to load your plugins in a way different than `require`

- **`pluckConfig`** - Allows you to override the configuration for `graphql-tag-pluck`. This tool extracts your GraphQL operations from your code files

  - **`pluckConfig.modules`** - An array of `{ name: string, identifier: string }` uses to track down your `gql` usages and imports. Use this if your code files import `gql` from another library or have a custom `gql` tag. `identifier` is the named export, so don't provide it if the tag function is imported as default

  - **`pluckConfig.gqlMagicComment`** - Configures the magic GraphQL comments to look for. The default is `/* GraphQL */`)

  - **`pluckConfig.globalGqlIdentifierName`** - Overrides the name of the default GraphQL name identifier

- **`skipDocumentsValidation`** - Allows to configure how to validate documents

  - **`skipDocumentsValidation.skipValidationAgainstSchema`** - A flag to disable the validation against the schema

  - **`skipDocumentsValidation.ignoreRules`** - An array of rule names to ignore during the validation. You can find a list of the available rules [here](https://github.com/graphql/graphql-js/tree/main/src/validation/rules)

  - **`skipDocumentsValidation.skipDuplicateValidation`** - A flag to disable the validation for duplicate documents

- **`allowPartialOutputs`** - Allows partial outputs to be written to files if one or more `generates` blocks have errors. Default is `false`.

## Environment Variables

You can use environment variables in your `codegen.ts` file:

```ts /process.env.SCHEMA_PATH/
import { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: process.env.SCHEMA_PATH,
  documents: ['src/**/*.tsx'],
  generates: {
    './src/gql/': {
      preset: 'client'
    }
  }
}

export default config
```

## CLI Flags

The Codegen also supports several CLI flags that allow you to override the default behavior specified in your `.yml` config file:

- **`--config` (`-c`)** - Specifies the codegen config file to use.

- **`--watch` (`-w`)** - Overrides the `watch` config to true. You can also specify a glob expression to create a custom watch list.

- **`--silent` (`-s`)** - Overrides the `silent` config to true.

- **`--verbose` (`-v`)** - Overrides the `verbose` config to true.

- **`--debug` (`-d`)** - Overrides the `debug` config to true.

- **`--errors-only` (`-e`)** - Overrides the `errorsOnly` config to true.

- **`--require` (`-r`)** - Specifies `require.extensions` before loading the `.yml` file.

- **`--overwrite` (`-o`)** - Overrides the `overwrite` config to true.

- **`--profile`** - Use the profiler to measure performance. _(see "Profiler" in "Advanced Usage")_

- **`--project` (`-p`)** - To generate only one project out of a [Multi Project](multiproject-config) config file.

- **`--check`** - Enable dry-run mode (see below)

## Dry-run mode

Codegen can be run in dry-run mode to check if some new changes are detected:

```bash
yarn run codegen --check
```

When enabled, codegen will return the following exit code:

- `0`: no changes were detected
- `1`: some changes are missing in existing files

<Callout type="warning">

**Using `--check` dry-run mode with prettyfied generated files**

Because the `--check` dry-run mode is comparing local files with
in-memory generated content, projects that runs Prettier on files generated with codegen will always end-up returning
all files as stale.

</Callout>

## Debug Mode

To enable debug mode, either set the `debug: true` configuration option or use the CLI `--debug` flag.

For more detailed output, you can also enable the `verbose: true` or `--verbose` CLI flag.

> `DEBUG=1` and `VERBOSE=1` environment variables are deprecated but still supported until the next major.

## Other ways to provide configuration

GraphQL-Codegen uses [`cosmiconfig`](https://github.com/davidtheclark/cosmiconfig) library to manage configuration loading.

That means you can use `codegen.yml`, `codegen.json`, `codegen.js`, or `codegen.ts` as configuration files. You can also specify the entire configuration under a key called `"codegen"` in your `package.json`.
For more information, [please refer to `cosmiconfig` documentation](https://github.com/davidtheclark/cosmiconfig#cosmiconfig).

For TypeScript files, GraphQL-Codegen uses [`jiti` loader](https://github.com/unjs/jiti) to load the configuration. That means you can additionally use `.mts`, and `.cts` extensions.

GraphQL-Codegen is also integrable with [GraphQL-Config](https://graphql-config.com), so you can specify `.graphqlrc` as your configuration file.
